/**
 * 
 */
package com.shuqi.activity.viewport;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shuqi.activity.BookSearchParentActivity;
import com.shuqi.activity.adapter.BookSearchParentAdapter;
import com.shuqi.common.Constant;
import com.shuqi.common.PageIndicator;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;

/**
 * 搜索顶部标签栏滑动view
 * 
 * @author linyuren
 * 
 */
public class BookSearchTabSlidingView extends RelativeLayout implements PageIndicator {

    private View view;
    private TextView mSlidingTvHotlist;
    private TextView mLidingTvman;
    private TextView mSlidingTvwoman;
    private TextView mSlidingTvall;
    private View animation;

    private ViewPager mViewPager;
    private PagerAdapter mPagerAdapter;
    private OnSelectedListener listener;
    /** 水平偏移量 */
    private int horizontalOffset;

    public BookSearchTabSlidingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        view =
                LayoutInflater.from(context).inflate(R.layout.search_view_slidingview_title, this,
                        false);
        mSlidingTvHotlist = (TextView) view.findViewById(R.id.sliding_tvhotlist);
        mLidingTvman = (TextView) view.findViewById(R.id.sliding_tvman);
        mSlidingTvwoman = (TextView) view.findViewById(R.id.sliding_tvwoman);
        mSlidingTvall = (TextView) view.findViewById(R.id.sliding_tvall);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.groove);
        String titles = a.getString(R.styleable.groove_titleArray);
        a.recycle();
        setTexts(titles);
        // 控件添加到定义View中
        addView(view);
        // 添加移动模块
        initAnimationView();
    }

    /**
     * 设置显示的内容,用"_"隔开
     */
    public void setTexts(String titles) {
        String[] titleArray = titles.split("_");
        mSlidingTvHotlist.setText(titleArray[0]);
        mLidingTvman.setText(titleArray[1]);
        mSlidingTvwoman.setText(titleArray[2]);
        mSlidingTvall.setText(titleArray[3]);
    }

    /**
     * 设置页面被切换至索引页的监听事件
     * 
     * @param listener
     */
    public void setOnSelectedListener(OnSelectedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        int width = mSlidingTvHotlist.getWidth();
        final int leftMargin = (int) (position * width + width * positionOffset);
        post(new Runnable() {
            public void run() {
                scrollTo(leftMargin);
            }
        });

    }

    private void scrollTo(int x) {
        if (animation == null) {
            return;
        }
        RelativeLayout.LayoutParams params = (LayoutParams) animation.getLayoutParams();
        params.leftMargin = x + (horizontalOffset / 2);
        animation.setLayoutParams(params);
    }

    private int initPosition;

    /**
     * 设置按钮的位置
     * 
     * @param site 从1开始
     */
    public void setSite(int site) {
        // 设置选中的字体颜色大小
        setTextColor(site);
        initPosition = site;
        if (animation != null) {
            scrollTo(initPosition * mSlidingTvHotlist.getWidth());
        }
    }

    /**
     * 设置按钮的点击事件
     * 
     * @param site 从1开始
     * @param listener
     */
    public void setOnClickListener(int site, OnClickListener listener) {
        switch (site) {
            case Constant.SLIDING_0:
                mSlidingTvHotlist.setOnClickListener(listener);
                break;
            case Constant.SLIDING_1:
                mLidingTvman.setOnClickListener(listener);
                break;
            case Constant.SLIDING_2:
                mSlidingTvwoman.setOnClickListener(listener);
                break;
            case Constant.SLIDING_3:
                mSlidingTvall.setOnClickListener(listener);
                break;
            default:
                break;
        }
    }

    /**
     * 移动按钮到指定位置
     * 
     * @param targetPosition 目标位置
     * @param hasAnim
     */
    public void moveAnim(final int targetPosition, final boolean hasAnim) {
        if (animation == null) {
            initAnimationView();
            return;
        }
        int width = mSlidingTvHotlist.getWidth();
        final int targetMargin = targetPosition * width;
        if (hasAnim) {
            RelativeLayout.LayoutParams params = (LayoutParams) animation.getLayoutParams();

            final int sourceMargin = params.leftMargin;
            new Thread() {
                @Override
                public void run() {
                    for (int i = 1; i < 35; i++) {
                        try {
                            sleep(10);
                        } catch (Exception e) {
                        }
                        final int t = i;
                        ((Activity) getContext()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                scrollTo(sourceMargin + (targetMargin - sourceMargin) * t / 35);
                            }
                        });
                    }
                    try {
                        sleep(20);
                    } catch (Exception e) {
                    }
                    post(new Runnable() {
                        @Override
                        public void run() {
                            scrollTo(targetMargin);
                        }
                    });
                }
            }.start();
        } else {
            scrollTo(targetMargin);
        }
        initPosition = targetPosition;
    }

    @Override
    public void onPageSelected(int position) {
        // 判断滑动完成后，改天字体大小和颜色
        setTextColor(position);
        if (listener != null) {
            listener.onSelected(position);
        }
        if (mPagerAdapter == null) {
            return;
        }
        if (mPagerAdapter instanceof BookSearchParentAdapter) {
            ((BookSearchParentAdapter) mPagerAdapter).notifyOnPageSelected(position);
        }
    }

    /**
     * 设置顶部滑动文字颜色
     * 
     * @param index
     */
    private void setTextColor(int index) {
        if (getContext() instanceof BookSearchParentActivity) {
            mSlidingTvHotlist.setTextColor(getResources().getColor(
                    R.color.booksearch_tabslidingview_top_title_up));
            mLidingTvman.setTextColor(getResources().getColor(
                    R.color.booksearch_tabslidingview_top_title_up));
            mSlidingTvwoman.setTextColor(getResources().getColor(
                    R.color.booksearch_tabslidingview_top_title_up));
            mSlidingTvall.setTextColor(getResources().getColor(
                    R.color.booksearch_tabslidingview_top_title_up));

            switch (index) {
                case Constant.SLIDING_0:
                    mSlidingTvHotlist.setTextColor(getResources().getColor(
                            R.color.booksearch_tabslidingview_top_title_press));
                    break;
                case Constant.SLIDING_1:
                    mLidingTvman.setTextColor(getResources().getColor(
                            R.color.booksearch_tabslidingview_top_title_press));
                    break;
                case Constant.SLIDING_2:
                    mSlidingTvwoman.setTextColor(getResources().getColor(
                            R.color.booksearch_tabslidingview_top_title_press));
                    break;
                case Constant.SLIDING_3:
                    mSlidingTvall.setTextColor(getResources().getColor(
                            R.color.booksearch_tabslidingview_top_title_press));
                    break;
            }
        }
    }

    @Override
    public void setViewPager(ViewPager view) {
        if (mViewPager == view) {
            return;
        }
        if (mViewPager != null) {
            mViewPager.setOnPageChangeListener(null);
        }
        mPagerAdapter = view.getAdapter();
        if (mPagerAdapter == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        mViewPager = view;
        mViewPager.setOnPageChangeListener(this);
        invalidate();
    }

    @Override
    public void setViewPager(ViewPager view, int initialPosition) {
        setViewPager(view);
        setCurrentItem(initialPosition);
    }

    @Override
    public void setCurrentItem(int item) {

    }

    @Override
    public void setOnPageChangeListener(OnPageChangeListener listener) {

    }

    @Override
    public void notifyDataSetChanged() {

    }

    private void initAnimationView() {
        if (animation != null) {
            return;
        }
        horizontalOffset = Util.dip2px(getContext(), 32);
        final int slidingHeight = Util.dip2px(getContext(), 1.5f);
        final int spaceBottom = Util.dip2px(getContext(), 1);
        BookSearchTabSlidingView.this.getViewTreeObserver().addOnPreDrawListener(
                new OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        final int width = mSlidingTvHotlist.getWidth() - horizontalOffset;
                        if (animation == null) {
                            animation = new View(view.getContext());
                            animation.setBackgroundColor(getResources().getColor(
                                    R.color.booksearch_tabslidingview_top_title_press));
                            RelativeLayout.LayoutParams rl =
                                    new RelativeLayout.LayoutParams(width, slidingHeight);
                            rl.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                            rl.setMargins(0, 0, 0, spaceBottom);
                            BookSearchTabSlidingView.this.addView(animation, rl);
                            scrollTo(initPosition * width);
                        }
                        BookSearchTabSlidingView.this.getViewTreeObserver()
                                .removeOnPreDrawListener(this);
                        return true;
                    }
                });

    }

    public interface OnSelectedListener {
        /**
         * 切换至页面索引
         */
        void onSelected(int position);
    }


}
